<template>
  <div class="dashboard-container">
    <!--第一横栏开始-->
    <el-row>
      <el-col :span="4">
        <p style="font-size: larger">新建编辑缺陷</p>
      </el-col>
      <el-col :offset="16" :span="4" style="margin-top: 15px">
        <span><el-button @click="submit">提交</el-button></span>
        <span style="margin-left: 20px"><el-button @click="back">返回</el-button></span>
      </el-col>
    </el-row>
    <!--第一横栏结束-->
    <el-divider></el-divider>
    <!--第二横栏开始-->
    <div style="margin-left: 100px;width: 600px;">
      <el-form :model="formData" class="demo-ruleForm" label-width="95px">
        <el-form-item label="缺陷名称:" prop="title" :required="true">
          <el-input v-model="formData.title"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="11">
            <el-form-item label="角色选择：" :required="true">
              <el-select v-model="formData.selectRole" placeholder="---选择角色---" @change="selectRole">
                <el-option
                  v-for="item in role"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="处理人：" :required="true">
              <el-select v-model="formData.handlerId" placeholder="---选择处理人---">
                <el-option
                  v-for="item in handler"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="项目模块：" :required="true">
              <el-select v-model="formData.moduleName" placeholder="---选择项目模块---">
                <el-option
                  v-for="item in proModule"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="缺陷类别：" :required="true">
              <el-select v-model="formData.bugCategory" placeholder="---选择缺陷类别---">
                <el-option
                  v-for="item in bugCategory"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="严重等级：" :required="true">
              <el-select v-model="formData.ponderance" placeholder="---选择严重等级---">
                <el-option label="致命" value="致命"></el-option>
                <el-option label="严重" value="严重"></el-option>
                <el-option label="一般" value="一般"></el-option>
                <el-option label="较小" value="较小"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="出现频率：" :required="true">
              <el-select v-model="formData.frequency" placeholder="---选择出现频率---">
                <el-option label="总是" value="总是"></el-option>
                <el-option label="通常" value="通常"></el-option>
                <el-option label="有时" value="有时"></el-option>
                <el-option label="很少" value="很少"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="13">
            <el-form-item label="缺陷的优先级：" label-width="50" :required="true">
              <el-select v-model="formData.priority" placeholder="---选择缺陷的优先级---">
                <el-option label="立即解决" value="立即解决"></el-option>
                <el-option label="高优先级" value="高优先级"></el-option>
                <el-option label="正常排队" value="正常排队"></el-option>
                <el-option label="低优先级" value="低优先级"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="0" :span="11">
            <el-form-item label="关联用例：" prop="associateExample">
              <!-- <el-select @focus="selectExample" v-model="formData.exampleId" filterable placeholder="请选择关联用例">
                <el-option
                  v-for="item in exampleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select> -->
              <el-input placeholder="选择关联的用例" @focus="selectExample" v-model="currentExample.exampleName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="缺陷描述：" :required="true">
          <el-input placeholder="填写缺陷描述信息" type="textarea" v-model="formData.bugDescription"></el-input>
        </el-form-item>
        <el-form-item label="附件上传：">
          <el-upload
            class="upload-demo"
            action=""
            ref="upload"
            multiple
            :limit="3"
            :http-request="submitUpload"
            :data="{'bugId':bugId}"
            :file-list="formData.fileList"
            :on-change="filesChange"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
            <el-button v-if="formData.id!=null" style="margin-left: 60px" size="small" type="danger" @click="additionalDocuments(formData.id)">补加附件</el-button>
          </el-upload>
        </el-form-item>
        <el-alert
          v-if="formData.id!=null"
          style="width: 80%;color: #9c631d"
          type="warning"
          :closable="false"
        >
          <template slot="title">
            <div style="font-size: 120%">温馨提示:</div>
            <div>1.请将所有选项选择完整，否则将出现未知错误。</div>
            <div>2.如果只是添加附件，只需要选择点击上传，然后点击补加附件即可。请勿点击提交按钮</div>
          </template>
        </el-alert>
        <el-form-item>
          <span><el-button @click="submit">提交</el-button></span>
          <span style="margin-left: 20px"><el-button @click="back">返回</el-button></span>
        </el-form-item>
      </el-form>
    </div>
    <!--第二横栏结束-->

    <!-- 选择关联用例的弹窗 -->
    <el-dialog
      title="选择用例"
      :visible.sync="dialogVisible"
      width="65%">
      <span class="select-example">
        <div style="width: 40%;margin-left: 60%">
          <el-input placeholder="请输入用例" v-model="searchExample">
            <template slot="append">
              <el-button  type="primary" icon="el-icon-search" @click="searchClick">搜索</el-button>
            </template>
          </el-input>
        </div>
      </span>
      <span>
        <el-table
          ref="singleTable"
          :data="exampleOptions"
          @current-change="handleCurrentChange"
          highlight-current-row
          style="width: 100%">
          <el-table-column
            label="用例编号"
            show-overflow-tooltip
            width="150"
            prop="exampleName">
          </el-table-column>
          <el-table-column
            label="测试项"
            show-overflow-tooltip
            width="100"
            prop="testItems">
          </el-table-column>
          <el-table-column
            label="制作人"
            show-overflow-tooltip
            width="70"
            prop="producer">
          </el-table-column>
          <el-table-column
            label="预期结果"
            show-overflow-tooltip
            width="150"
            prop="expectedOutcome">
          </el-table-column>
          <el-table-column
            label="bug数量"
            show-overflow-tooltip
            width="80"
            prop="bugNumber">
          </el-table-column>
          <el-table-column
            label="用例描述"
            show-overflow-tooltip
            width="120"
            prop="exampleDescription">
          </el-table-column>
          <el-table-column
            label="创建时间"
            show-overflow-tooltip
            :formatter="formatDate"
            width="150"
            prop="createTime">
          </el-table-column>
        </el-table>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button class="proButton" @click="selectExampleSucess">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { addBug, getModule, inquirerByProjectIdAndRole, updateBug, uploadFiles } from '@/api/bug'
  import { getExamplesNoye,getExamplesVague } from '@/api/example'

  export default {
    name: 'createBug',
    data() {
      return {
        pagesize: 7,        //分页每一页的数目
        currentPage: 1,     //标记当前的在第几页
        total: 0,
        //表单绑定的数据
        formData: {
          title: '',               //缺陷名称
          selectRole: '',          //角色选择
          handlerId: '',           //处理人选择
          moduleName: '',          //项目模块选择
          bugCategory: '',         //缺陷类别选择
          ponderance: '',          //缺陷等级选择
          frequency: '',           //缺陷频率
          priority: '',            //缺陷的优先级
          exampleId: '',           //关联用例
          bugDescription: '',      //缺陷描述
          fileList: [],            //文件上传集合
        },
        exampleOptions: [],        //用例数组  
        //角色选择数组
        role: [{
          value: '1',
          label: '项目经理'
        },{
          value: '2',
          label: '开发工程师'
        },{
          value: '3',
          label: '测试工程师'
        }],
        //处理人选择数组
        handler: [],
        //项目模块数组
        proModule: [],
        //bug的id
        bugId: '',
        //缺陷类别数组
        bugCategory: [{
          value: '功能缺陷',
          label: '功能缺陷'
        }, {
          value: '接口缺陷',
          label: '接口缺陷'
        }, {
          value: '验证缺陷',
          label: '验证缺陷'
        }, {
          value: '软件包缺陷',
          label: '软件包缺陷'
        }, {
          value: '文档缺陷',
          label: '文档缺陷'
        }, {
          value: '算法缺陷',
          label: '算法缺陷'
        }, {
          value: '用户界面缺陷',
          label: '用户界面缺陷'
        }, {
          value: '性能缺陷',
          label: '性能缺陷'
        }, {
          value: '准则缺陷',
          label: '准则缺陷'
        }],
        files: [],
        dialogVisible: false,   //绑定用例的弹窗
        searchExample: "",      //用于模糊查询的用例字段
        currentExample: {exampleName:''},     //当前选择的用例
      }
    },
    computed:{
      ...mapGetters(['projectId','userInfo'])
    },
    methods: {
      //选择文件时文件列表改变的方法
      filesChange(file){
        this.files = file.raw
      },
      //提交文件到后台的方法
      submitUpload(bugId) {
        let params = new FormData()
        if (this.files.length === 0){
          return;
        }
        params.append('files',this.files)
        params.append('bugId',bugId)
        uploadFiles(params).then(res =>{
          console.log(res)
        })
      },
      //提交按钮调用的方法
      submit() {
        this.loading = true
        if (this.formData.id != null){
          let params = this.formData
          params.createTime = new Date(params.createTime)
          params.updateTime = new Date(params.updateTime)
          updateBug(params).then(res =>{
            this.$message({type:'success',message:res.msg})
            this.$router.push("/proDetails/bugManage")
          })
        }else{
          this.$set(this.formData,'proId',this.projectId)
          this.$set(this.formData,'submitterId',this.userInfo.id)
          this.$set(this.formData,'bugStatus',"0")
          addBug(this.formData).then(res =>{
            this.$message({type:'success',message:res.msg})
            this.bugId = res.data
            this.submitUpload(res.data)
            this.$router.push("/proDetails/bugManage")
          })
        }
        this.loading = false
        return null;
      },
      //返回按钮调用的方法
      back() {
        this.$router.push('/proDetails/bugManage')
      },
      //选择了角色后动态获取处理人
      selectRole(val){
        let params = {'role':val,'proId': this.projectId}
        inquirerByProjectIdAndRole(params).then(res =>{
          this.handler = []
          this.formData.handlerId = ''
          for (let i = 0; i < res.data.length; i++){
            this.handler[i] = { value:res.data[i].userId,label: res.data[i].userName}
          }
        })
      },
      //补加附件按钮的方法
      additionalDocuments(bugId){
        this.submitUpload(bugId)
        this.back()
        this.$message({type:'success',message:'上传成功'})
      },
      //获取项目用例的方法
      getExample(){
        getExamplesNoye({"proId":this.projectId}).then(res =>{
          this.exampleOptions = res.data
        })
      },
      //模糊查询获取项目用例
      getExampleVague(){
        getExamplesVague({"exampleName":this.searchExample},this.projectId).then(res =>{
          this.exampleOptions = {}
          this.exampleOptions = res.data
        })
      },
      //点击搜索
      searchClick(){
        if(this.searchExample === "" || this.searchExample === null){
          this.getExample();
          console.log("我时1--"+this.searchExample)
        }else{
          this.getExampleVague()
          console.log("我时2"+this.searchExample)
          console.log(this.exampleOptions)
        }
      },
      //选择关联用例的弹出框显示的方法
      selectExample(){
        this.dialogVisible = true
      },
      //选择用例时的改变
      handleCurrentChange(val) {
        this.currentExample = val;
      },

      //确定选择的用例
      selectExampleSucess(){
        this.dialogVisible = false
        this.formData.exampleId = this.currentExample.id
        console.log(this.formData.exampleId)
      },

      //格式化时间
      formatDate(row, column) {
        // 获取单元格数据
        let data = row[column.property]
        if (data == null || data == "") {
            return ''
        }
        let dt = new Date(data)
        return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
      },
    },
    mounted(){
      if (this.$route.query.obj){
        let s = JSON.parse(decodeURIComponent(this.$route.query.obj))
        this.formData = s
        this.currentExample = {'exampleId': this.formData.exampleId,'exampleName':this.formData.exampleName}
      }
      //获取模块
      getModule(this.projectId).then(res =>{
        for (let i = 0; i < res.data.length; i++){
          this.proModule[i] = {value:res.data[i],label:res.data[i] }
        }
      })
      //获取用例
      this.getExample()
    },
  }
</script>

<style scoped>

 .select-example{
   width: 10%;
 }

 .select-example ::v-deep .el-input-group__append button.el-button, .el-input-group__append div.el-select .el-input__inner, .el-input-group__append div.el-select:hover .el-input__inner, .el-input-group__prepend button.el-button, .el-input-group__prepend div.el-select .el-input__inner, .el-input-group__prepend div.el-select:hover .el-input__inner {
    background-color: #409EFF; 
    color: #FFFFFF;
    border-radius: 0;
  }
</style>
